from  rest_framework import serializers
from .models import User
import re
from rest_framework_jwt.settings import api_settings
class UserSeralizer(serializers.ModelSerializer):
    '''
    用户序列化器
    '''
    password2 = serializers.CharField(label='确认密码',write_only=True)
    token = serializers.CharField(label='token',read_only=True)
    cn_is_superuser = serializers.SerializerMethodField(read_only=True)
    cn_is_active = serializers.SerializerMethodField(read_only=True)
    date_joined= serializers.CharField(read_only=True)

    class Meta:
        model= User

        fields = ['id','username','password','password2','first_name','email','weChat','mobile','is_active','is_superuser','token','cn_is_superuser','cn_is_active','date_joined']


    def get_cn_is_superuser(self,obj):
        '''
        管理员判断
        :param obj:
        :return:
        '''
        if obj.is_superuser == True:
            return '管理员'
        else:
            return '非管理员'

    def get_cn_is_active(self, obj):
        '''
        状态判断
        :param obj:
        :return:
        '''
        if obj.is_active == True:
            return '启用'
        else:
            return '停用'

    def validate(self,data):
        '''
        验证字段
        :param data:
        :return:
        '''

        password = data.get('password')
        password2 = data.get('password2')
        if  password != password2:
            raise serializers.ValidationError('2次密码输入不相同')
        elif password is None and password2 is None:
            raise serializers.ValidationError('输入密码为空')

        if not re.match(r'^1[3-9]\d{9}$', data.get('mobile')):
            raise serializers.ValidationError('手机号格式不对')

        pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
        if not re.match(pattern,  data.get('email')):
            raise serializers.ValidationError('不是有效的邮件地址')
        return data



    def create(self, validated_data):
        '''
        重写创建
        :param validated_data:
        :return:
        '''
        del validated_data['password2']
        myuser = User(**validated_data)
        myuser.set_password(validated_data['password'])
        myuser.save()
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 引用jwt中的叫jwt_payload_handler函数(生成payload)
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 函数引用 生成jwt
        #
        # payload = jwt_payload_handler(myuser)  # 根据user生成用户相关的载荷
        # token = jwt_encode_handler(payload)  # 传入载荷生成完整的jwt
        #
        # myuser.token = token

        return myuser

    def update(self, instance, validated_data):
        print(validated_data)
        '''修改'''
        del validated_data['password2']
        instance.username = validated_data['username']
        instance.first_name = validated_data['first_name']
        instance.email = validated_data['email']
        instance.weChat = validated_data['weChat']
        instance.mobile = validated_data['mobile']
        instance.is_active = validated_data['is_active']
        instance.is_superuser = validated_data['is_superuser']
        if validated_data['password'] is not None:
            instance.set_password(validated_data['password'])



        instance.save()
        # instance.password2 = instance.password
        return instance







